package com.server.service.impl;

import com.common.constant.MessageConstant;
import com.common.exception.AccountNotFoundException;
import com.common.exception.PasswordErrorException;
import com.common.exception.UserExistException;
import com.pojo.dto.UserDTO;
import com.pojo.entity.User;
import com.server.mapper.UserMapper;
import com.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;



@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        User user = userMapper.selectByUsername(username);
        if (user == null){
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码比对
        // 进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        //3、返回实体对象
        return user;
    }

    @Override
    public Integer register(UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        //判断是否存在
        User user = userMapper.selectByUsername(username);
        if (user != null){
            //用户已存在，抛出异常
            throw new UserExistException(MessageConstant.USER_EXIST);
        }
        //对密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        User user1 = User.builder()
                .username(username)
                .password(password).build();
        userMapper.insertUser(user1);

        return user1.getId();
    }
}
